import select
from socket import *

def main():
    serv_sock=socket(AF_INET,SOCK_STREAM)
    serv_sock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    serv_sock.bind(('',8888))
    serv_sock.setblocking(False)
    serv_sock.listen(128)



    myepoll=select.epoll()
    # 注册监听事件
    myepoll.register(serv_sock.fileno(),select.EPOLLIN|select.EPOLLET)
    #存储套接字
    sock_dict=dict()
    #存储地址
    sock_addr=dict()
    while True:
        #监听结果
        ep_list=myepoll.poll()
        for fd,event in ep_list:
            if fd==serv_sock.fileno():
                #有新的客户端请求
                client,addr=serv_sock.accept()
                client.setblocking(False)
                print('接收到%s的连接'%str(client))
                #把套接字对象和地址存储
                sock_dict[client.fileno()]=client
                sock_addr[client.fileno()]=addr
                myepoll.register(client.fileno(),select.EPOLLIN|select.EPOLLET)
            elif event==select.EPOLLIN:
                #表示ｄｆ上有可读对象
                while True:
                    try:
                        recv_data=sock_dict[fd].recv(1024)
                    except:
                        break
                    else:
                        if recv_data:
                            print(recv_data)
                        else:
                            print('%s断开连接'%str(sock_addr[fd]))
                            myepoll.unregister(fd)
                            sock_dict[fd].close()
                            del sock_dict[fd]
                            del sock_addr[fd]


if __name__ == '__main__':
    main()